package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	//timeTickerOne()
	//timeOnlyOnce()

	compareTimeTricker()
}

func compareTimeTricker() {
	ticker := time.NewTicker(time.Second)
	defer ticker.Stop()

	timeout, cancelFunc := context.WithTimeout(context.Background(), time.Second*5)
	defer cancelFunc()

	go func() {
		for {
			select {
			case <-timeout.Done():
				fmt.Println("timeout done")
				return
			case <-ticker.C:
				fmt.Println("定时器触发啦！")
			}
		}
	}()
	// 主goroutine等待 7 秒，确保看到定时器触发的输出
	//猜测下这里time.Sleep有什么作用？
	//time.Sleep(time.Second * 7)
}

// 实现一次性定时器。
func timeOnlyOnce() {
	select {
	case <-time.After(time.Second * 2):
		fmt.Println("Tick")
	}
}

// 网络模仿
func netImitate() {
	//这个会报错的
	/*
		// 模拟网络请求
		ch := make(chan int, 2)
		go func() {
			// 假设请求需要2秒钟才能得到响应
			time.Sleep(2 * time.Second)
			ch <- 1
		}()

		// 设置超时时间为1秒钟
		timeout := time.NewTimer(1 * time.Second)

		select {
		case <-ch:
			fmt.Println("Get response.")
		case <-timeout.C:
			fmt.Println("Timeout.")
		}

		// 停止定时器，释放资源
		if !timeout.Stop() {
			<-timeout.C
		}
	*/
}

func timeTickerOne() {
	ticker := time.NewTicker(1 * time.Second)
	defer ticker.Stop()
	for {
		select {
		case <-ticker.C:
			fmt.Println("Hello, world!")
		}
	}

	//猜测下这里time.Sleep会有什么影响？
	//time.Sleep(time.Second * 4)
}
